package com.jdpc.weparty.component

import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Configuration
import java.io.IOException
import java.util.*
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


//@WebFilter(value="/*",filterName = "aaaaaLoggingFilter" )
@Configuration
class LoggingFilterConfig : Filter {
//    @Bean
//    fun registrationBean(): FilterRegistrationBean<*> {
//        val filter = FilterRegistrationBean(LoggingFilterConfig())
//        filter.addUrlPatterns("/*")
//        //多个过滤器时执行顺序
//        // 最高级别。
//        filter.order = FilterRegistrationBean.HIGHEST_PRECEDENCE
//        return filter
//    }

    @Throws(ServletException::class)
    override fun init(filterConfig: FilterConfig?) {
    }

    @Throws(IOException::class, ServletException::class)
    override fun doFilter(request: ServletRequest, response: ServletResponse,
                          chain: FilterChain) {

        response as HttpServletResponse

        response.setHeader("Access-Control-Allow-Origin", "*")

        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD, PUT")

        response.setHeader("Access-Control-Max-Age", "3600")

        response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With, authorization")
        logRequest(request, response)
        chain.doFilter(request, response)

    }

    private fun logRequest(request: ServletRequest, response: ServletResponse) {
        // TODO Auto-generated method stub
        val req = request as HttpServletRequest
        val map: MutableMap<String, Any> = HashMap()

        // Get request URL.
        map["URL"] = req.requestURL
        map["Method"] = req.method
        map["Protocol"] = req.protocol
        // 获取header信息
        val headerList: MutableList<Map<String, String>> = ArrayList()
        val headerMaps: MutableMap<String, String> = HashMap()
        val enu = req.headerNames
        while (enu.hasMoreElements()) {
            val name = enu.nextElement()
            headerMaps[name] = req.getHeader(name)
        }
        headerList.add(headerMaps)
        map["headers"] = headerList
        //获取parameters信息
        val parameterList: MutableList<Map<String, String>> = ArrayList()
        val parameterMaps: MutableMap<String, String> = HashMap()
        val names = req.parameterNames
        while (names.hasMoreElements()) {
            val name = names.nextElement()
            parameterMaps[name] = req.getParameter(name)
        }
        parameterList.add(parameterMaps)
        map["parameters"] = parameterList
        var line: String? = ""
        // 获取请求体信息
//            if (req.getMethod().equalsIgnoreCase("POST")) {
//                int len = req.getContentLength();
//                char[] buf = new char[len];
//                int bufcount = requestWrapper.getReader().read(buf);
//                if (len > 0 && bufcount <= len) {
//                    line = String.copyValueOf(buf).substring(0, bufcount);
//                }
//            } else if (req.getMethod().equalsIgnoreCase("GET")) {
        val idx = req.requestURL.indexOf("?")
        line = if (idx != -1) {
            req.requestURL.substring(idx + 1)
        } else {
            null
        }
        //            }
        if (line != null) {
            map["Context"] = arrayOf(line)
        }

        log.info("\n" +
                "接收request报文：\n" +
                ObjectMapper().writeValueAsString(map).trimIndent()
        )

        // 辞书
        log.info("\n" +
                "接收response报文：\n" +
                response.contentType?.trimIndent()

        )
    }

    override fun destroy() {

    }

    companion object {
        private var log = LoggerFactory.getLogger(javaClass)
    }
}